package com.suian.controller;

import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricActivityInstanceQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/process")
public class ProcessController {
    private static final Logger log = LoggerFactory.getLogger(ProcessController.class);

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;

    //启动流程
    @PostMapping("/start")
    public String startProcess() {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("Process_1744640336119");

        return "流程已启动，ID: " + processInstance.getId() +"/n 任务Id";
    }

    //查询任务
    @PostMapping("/queryTask")
    public String queryTaskId(@RequestParam String processInstanceId) {
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        return Map.of("processInstanceId",processInstanceId,
                "taskId",task.getId(),
                "taskName",task.getName()).toString();
    }
    //完成当前任务
    @PostMapping("/complete")
    public String completeTask(@RequestParam String taskId,@RequestParam(name = "testFlag", defaultValue = "true") boolean testFlag) {
        try {
            taskId = String.valueOf(2 / 0);
            taskService.complete(taskId);
            return "任务完成";
        } catch (Exception e) {
            return handleRollback(taskId, e);
        }

    }

    private String handleRollback(String currentTaskId, Exception e) {
        //获取当前任务
        Task currentTask = taskService.createTaskQuery()
                .taskId(currentTaskId)
                .singleResult();

        //获取历史活动实例（倒叙）
        List<HistoricActivityInstance> activities = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(currentTask.getProcessInstanceId())
                .orderByHistoricActivityInstanceEndTime().desc()
                .list();

        //查询上一个用户任务
        String rollbackTargetId = null;
        for (HistoricActivityInstance activity : activities) {
            if ("userTask".equals(activity.getActivityType()) && !activity.getActivityId().equals(currentTask.getTaskDefinitionKey())) {
                rollbackTargetId = activity.getActivityId();
                break;
            }
        }

        if (rollbackTargetId != null) {
            //创建回退
            runtimeService.createChangeActivityStateBuilder()
                    .processInstanceId(currentTask.getProcessInstanceId())
                    .moveActivityIdTo(currentTask.getTaskDefinitionKey(), rollbackTargetId)
                    .changeState();
            return "任务回退到：" + rollbackTargetId;
        }
        return "无法回退：" + e.getMessage();
    }
}




















